import { HttpConfig } from './HttpConfig';
import { HttpQueue } from './HttpQueue';
import { HttpStorage } from './HttpStorage';
import { Http } from './Http';

export interface RefreshTokenResponse {
  token: string;
  refreshToken: string;
}

export class HttpTokenManager {
  private static _refreshing = false;

  static async handleAuthError() {
    if (this._refreshing) return;

    this._refreshing = true;
    const refreshToken = HttpStorage.get('refreshToken');
    if (!refreshToken) {
      this.failAll();
      return;
    }

    try {
      const res = await Http.post<RefreshTokenResponse>(
        HttpConfig.refreshTokenUrl,
        { refreshToken },
        { skipAuth: true }
      );

      const { token, refreshToken: newRefresh } = res;
      HttpStorage.set('token', token);
      HttpStorage.set('refreshToken', newRefresh);
      HttpQueue.replayAll(); // ✅ 重新执行挂起请求
    } catch (e) {
      this.failAll(); 
    } finally {
      this._refreshing = false;
    }
  }

  private static failAll() {
    HttpStorage.clear();
    HttpQueue.clear();
    HttpConfig.redirectToLogin();
  }
}
